from django.shortcuts import render, get_object_or_404

# Create your views here.
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from cart.models import CartItem
from .models import Order, OrderItem
import random
import string
from decimal import Decimal


def generate_order_number():
    """生成随机订单号"""
    return ''.join(random.choices(string.ascii_uppercase + string.digits, k=12))


@login_required
def checkout(request):
    cart_items = CartItem.objects.filter(user=request.user)
    if not cart_items:
        messages.warning(request, '购物车为空，无法结算')
        return redirect('cart_view')

    if request.method == 'POST':
        # 创建订单
        total_amount = sum(item.product.price * item.quantity for item in cart_items)
        order = Order.objects.create(
            user=request.user,
            order_number=generate_order_number(),
            total_amount=total_amount,
            shipping_address=request.POST.get('shipping_address'),
            contact_phone=request.POST.get('contact_phone')
        )

        # 创建订单项
        for cart_item in cart_items:
            OrderItem.objects.create(
                order=order,
                product=cart_item.product,
                quantity=cart_item.quantity,
                price=cart_item.product.price
            )

        # 清空购物车
        cart_items.delete()

        # 重定向到订单详情页面
        messages.success(request, '订单创建成功！')
        return redirect('order_detail', order_id=order.id)

    return render(request, 'orders/checkout.html', {'cart_items': cart_items})

@login_required
def order_list(request):
    orders = Order.objects.filter(user=request.user)
    return render(request, 'orders/order_list.html', {'orders': orders})


@login_required
def order_detail(request, order_id):
    order = Order.objects.get(id=order_id, user=request.user)
    return render(request, 'orders/order_detail.html', {'order': order})


@login_required
def payment(request, order_id):
    order = Order.objects.get(id=order_id, user=request.user)
    if request.method == 'POST':
        # 这里模拟支付成功
        order.status = 'paid'
        order.save()
        messages.success(request, '支付成功！')
        return redirect('order_detail', order_id=order.id)

    return render(request, 'orders/payment.html', {'order': order})

@login_required
def process_payment(request, order_id):
    order = get_object_or_404(Order, id=order_id, user=request.user)
    if order.status == 'pending':
        # 模拟支付成功
        order.status = 'paid'
        order.save()
        messages.success(request, '支付成功！')
    return redirect('order_detail', order_id=order.id)  # 直接重定向到订单详情页面